package com.health.viewscontrols.medical.device.bf;

import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.health.tablebean.BTDevice;
import com.health.viewscontrols.NovaApplication;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.twj.PwBean;

import java.util.List;
import java.util.UUID;

/**
 * 血脂（E家医护）
 */
public class BFEjyhActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE_PW =
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
    public final static UUID UUID_NOTIFY_PW =
            UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1

    private long firstTime = 0;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bf_ejyh);
        mBleDevice.setDevice_Service_UUID(UUID_SERVICE_PW);
        mBleDevice.setDevice_Notify_UUID(UUID_NOTIFY_PW);
        mBleDevice.setConnectChangedListener(new OnDeviceConnectChangedListener() {
            @Override
            public void onConnected() {
                runOnUiThread(() -> {
                    //连接成功
                    Log.e(TAG, "onConnectSuccess: ");
                    isConnected = true;
                    blueToothState.setText("蓝牙已连接");
                    cancelProgressDialog();
                });
            }

            @Override
            public void onDisconnected() {
                runOnUiThread(() -> {
                    isConnected = false;
                    blueToothState.setText("蓝牙连接失败");
                    cancelProgressDialog();
                });
            }
        });
        startDevice();
    }


    private void connectDevice() {
        mBleDevice.setConnect(true);
        mBleDevice.setMAC(deviceEnum.getMac());
        mBleDevice.connect(deviceEnum.getMac());
    }

    @Override
    public void startDevice() {
        showProgressDialog("正在连接" + deviceEnum.getTitle());
        if (!isConnected) {
            blueToothState.setText("蓝牙开始连接");
            connectDevice();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!isConnected) {
                        connectDevice();
                    }
                }
            }, 3200);
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
        }
    }

    @Override
    public void update(String hexStr) {
        try {
            if (hexStr.length() > 10) {
                StringBuilder stringBuilder = new StringBuilder();
                String cmd = hexStr.substring(4, 6);
                System.out.println(cmd);
                //06代表测试结果
                if ("05".equals(cmd)) {
                    String data1 = hexStr.substring(8, 10);
                    if ("01".equals(data1)) {
                        tv_state.setText("光化学试纸插入");
                        Log.e(TAG, "光化学试纸插入 ");
                    } else if ("02".equals(data1)) {
                        tv_state.setText("光化学试纸拔出");
                        Log.e(TAG, "光化学试纸拔出 ");
                    } else if ("03".equals(data1)) {
                        tv_state.setText("光化学试纸合格");
                        Log.e(TAG, "光化学试纸合格 ");
                    } else if ("04".equals(data1)) {
                        tv_state.setText("光化学试纸过期");
                        Log.e(TAG, "光化学试纸过期 ");
                    } else if ("05".equals(data1)) {
                        tv_state.setText("光化学试纸已滴血,请等待测量结果");
                        Log.e(TAG, "光化学试纸已滴血");
                    }
                } else if ("06".equals(cmd)) {
                    PwBean pwBean = new PwBean();
                    Log.e(TAG, "测量完成");
                    //DATA1：01代表血脂卡
                    String data1 = hexStr.substring(8, 10);
                    System.out.println(data1);
                    if ("01".equals(data1)) {
                        String data2 = hexStr.substring(10, 12);
                        String data3 = hexStr.substring(12, 14);
                        int checkTc = checkDataCompliance(data2, data3);
                        if (checkTc == 1) {
                            double tc = (Integer.parseInt(data2, 16) * 256 + Integer.parseInt(data3, 16)) / 100.0;
                            pwBean.setTc(tc);
                            stringBuilder.append("总胆固醇:" + tc + "mmol/L" + "\n");
                        } else if (checkTc == 2) {
                            stringBuilder.append("总胆固醇:测试结果大于测试范围");
                        } else if (checkTc == 3) {
                            stringBuilder.append("总胆固醇:测试结果小于测试范围");
                        }

                        String data4 = hexStr.substring(14, 16);
                        String data5 = hexStr.substring(16, 18);
                        int checkTg = checkDataCompliance(data4, data5);
                        if (checkTg == 1) {
                            double tg = (Integer.parseInt(data4, 16) * 256 + Integer.parseInt(data5, 16)) / 100.0;
                            pwBean.setTg(tg);
                            stringBuilder.append("甘油三酯:" + tg + "mmdl/L\n");
                        } else if (checkTg == 2) {
                            stringBuilder.append("甘油三酯:测试结果大于测试范围");
                        } else if (checkTg == 3) {
                            stringBuilder.append("甘油三酯:测试结果小于测试范围");
                        }

                        String data6 = hexStr.substring(18, 20);
                        String data7 = hexStr.substring(20, 22);
                        int checkHdl = checkDataCompliance(data6, data7);
                        if (checkHdl == 1) {
                            double hdl = (Integer.parseInt(data6, 16) * 256 + Integer.parseInt(data7, 16)) / 100.0;
                            pwBean.setHdl(hdl);
                            stringBuilder.append("高密:" + hdl + "mmdl/L\n");
                        } else if (checkHdl == 2) {
                            stringBuilder.append("高密:测试结果大于测试范围");
                        } else if (checkHdl == 3) {
                            stringBuilder.append("高密:测试结果小于测试范围");
                        }

                        String data8 = hexStr.substring(22, 24);
                        String data9 = hexStr.substring(24, 26);
                        int checkLdl = checkDataCompliance(data8, data9);
                        if (checkLdl == 1) {
                            double ldl = (Integer.parseInt(data8, 16) * 256 + Integer.parseInt(data9, 16)) / 100.0;
                            pwBean.setLdl(ldl);
                            stringBuilder.append("低密:" + ldl + "mmdl/L\n");
                        } else if (checkLdl == 2) {
                            stringBuilder.append("低密:测试结果大于测试范围");
                        } else if (checkLdl == 3) {
                            stringBuilder.append("低密:测试结果小于测试范围");
                        }
                    }

                    Log.e(TAG, "resultData: " + stringBuilder.toString());
                    if (pwBean.getTc() > 0) {
                        tv_state.setText("获取测量结果成功");
                        tv_result.setText(stringBuilder.toString());

                        //有效数据在存入数据库
                        String json = GsonUtils.toJson(pwBean);
                        Log.e(TAG, "resultData: " + json);
                        long currentTime = System.currentTimeMillis();
                        if (currentTime - firstTime > 2000) {
                            firstTime = currentTime;
                            DeviceShowSaveData.getDataShow(json, BluetoothConstant.PW_01DEVICE_NAME);
                            DeviceShowSaveData.saveXueZhi(json);
                        }
                        cancelProgressDialog();
                    } else {
                        tv_state.setText("测量结果异常");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "出错了: " + e.getMessage());
        }
    }

    /**
     * 校验数据是否合规
     *
     * @return 1 合规 ；2 大于测试范围 ；3小于测试范围
     */
    public int checkDataCompliance(String params1, String params2) {
        if ("ff".equals(params1) && "ff".equals(params2)) {
            System.out.println("测试结果大于测试范围");
            return 2;
        } else if ("00".equals(params1) && "00".equals(params2)) {
            System.out.println("测试结果小于测试范围");
            return 3;
        } else {
            return 1;
        }
    }


    @Override
    public void disconnectDevice() {
        try {
            mBleDevice.setConnect(false);
            mBleDevice.disconnect();
            mBleDevice.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
